/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-05-31 13:44:24
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2023-06-25 15:54:03
 * @FilePath: \greenbeeadmin\controllers\admin\service\userService.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package service

import (
	"fmt"
	greebeeUtils "greenbeeadmin/controllers/greenbee/utils"
	"greenbeeadmin/models"
	"strconv"

	"github.com/beego/beego/v2/client/orm"
)

/**
 * @description: 角色 service
 * @return {*}
 */
type RoleService struct {
	AdminBaseService
}

type AdminRoleSearchParams struct {
	Rolename string
}

/**
 * @description: 获取后台角色列表数据
 * @param {map[string]string} params 搜索参数
 * @param {string} field 要查询的后台角色字段 全部数据传 “*”
 * @return {*}
 */
func (s *RoleService) GetList(params map[string]string, field []string) ([]models.Role, float64, error) {
	tableName := new(models.Role).GetTableName()
	var roles []models.Role
	rolename, ok := params["rolename"]
	where := "is_del =0"
	if ok {
		where += " and label like '%" + rolename + "%'"
	}
	pg, ok := params["page"]
	if ok {
		Page, _ = strconv.ParseFloat(pg, 64)
	} else {
		Page, _ = strconv.ParseFloat("1", 64)
	}
	limit_str, ok := params["limit"]
	if ok {
		Limit, _ = strconv.ParseFloat(limit_str, 64)
	} else {
		Limit, _ = strconv.ParseFloat("9999", 64)
	}
	//查询角色数据
	o := orm.NewOrm()
	//获取总条数
	var total_row float64
	o.Raw("select  count(id) from " + tableName + " as r where " + where).QueryRow(&total_row)
	//获取偏移值
	offset := greebeeUtils.GetPageOffset(Page, Limit, total_row)
	// 获取 QueryBuilder 对象. 需要指定数据库驱动参数。
	// 第二个返回值是错误对象，在这里略过
	qb, _ := orm.NewQueryBuilder("mysql")
	// 构建查询对象
	qb.Select(field...).
		From(tableName).
		Where(where).
		OrderBy("sort").Desc().
		Limit(int(Limit)).Offset(int(offset))

	// 导出 SQL 语句
	sql := qb.String()

	// 执行 SQL 语句
	o.Raw(sql).QueryRows(&roles)

	return roles, total_row, nil
}

/**
 * @description: 角色删除
 * @param {int} id
 * @return {*}
 */
func (s *RoleService) RoleDelete(id int) int64 {
	o := orm.NewOrm()
	role := models.Role{Id: id}
	if o.Read(&role) == nil {
		// 删除该角色权限
		s.DelRoleMenuId(id)

		role.Is_del = 1
		role.DeletedAt = greebeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", 0)
		if num, err := o.Update(&role); err == nil {
			//fmt.Println(num)
			return num
		}
	}
	return 0
}

/**
 * @description: 角色删除 批量
 * @param {[]string} ids
 * @return {*}
 */
func (s *RoleService) RoleDeletes(ids []string) int64 {
	var num int64
	o := orm.NewOrm()
	update_fmt := greebeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", 0)
	for _, id := range ids {
		id_int, _ := strconv.Atoi(id)
		role := models.Role{Id: id_int}
		if o.Read(&role) == nil {
			// 删除该角色权限
			s.DelRoleMenuId(id_int)
			role.Is_del = 1
			role.DeletedAt = update_fmt
			if num, err := o.Update(&role); err == nil {
				// fmt.Println(num)
				num += num
			}
		}
	}
	return num
}

/**
 * @description: 角色添加
 * @param {models.Role} roledata
 * @return {*}
 */
func (s *RoleService) RoleAdd(roledata models.Role) int64 {
	o := orm.NewOrm()
	id, err := o.Insert(&roledata)
	if err == nil {
		//fmt.Println(id)
	}
	return id
}

/**
 * @description: 角色编辑
 * @param {models.Role} roledata
 * @return {*}
 */
func (s *RoleService) RoleEdit(roledata models.Role, uid int, field []string) int64 {
	o := orm.NewOrm()
	user := models.Role{Id: uid}
	if o.Read(&user, "Id") == nil {
		if num, err := o.Update(&roledata, field...); err == nil {
			fmt.Println(num)
			return num
		}
	}
	return 0
}

/**
 * @description: 获取角色
 * @param {models.Role} roledata
 * @param {[]string} field
 * @return {*}
 */
func (s *RoleService) GetRole(roledata models.Role, field []string) (models.Role, error) {
	o := orm.NewOrm()
	err := o.Read(&roledata, field...)
	if err == orm.ErrNoRows {
		fmt.Println("查询不到")
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
	}
	return roledata, err
}

/**
 * @description: 角色授权
 * @param {int} id
 * @param {[]string} ids
 * @return {*}
 */
func (s *RoleService) RoleEmpower(roleId int, ids []string) int64 {
	var num int64
	o := orm.NewOrm()
	//删除角色下的id
	roleMenu := models.RoleMenu{RoleId: roleId}
	if _, err := o.Delete(&roleMenu, "RoleId"); err == nil {
		//fmt.Println(num)
		//插入 新菜单节点id
		if len(ids) > 0 {
			var insertData []models.RoleMenu
			for _, id := range ids {
				id_int, _ := strconv.Atoi(id)
				roleMenus := models.RoleMenu{RoleId: roleId, AdminMenuId: id_int}
				insertData = append(insertData, roleMenus)
			}
			successNum, _ := o.InsertMulti(len(insertData), insertData)
			return successNum
		}

	}

	return num
}

// 删除角色的权限
func (s *RoleService) DelRoleMenuId(roleId int) int64 {
	var num int64
	o := orm.NewOrm()
	//删除角色下的id
	roleMenu := models.RoleMenu{RoleId: roleId}
	if _, err := o.Delete(&roleMenu, "RoleId"); err == nil {
		num = 1
	}
	return num
}

/**
 * @description: 查询角色的 菜单id
 * @param {int} roleId
 * @return {*}
 */
func (s *RoleService) GetRoleMenusIds(roleId int) []int {
	var data []int
	var roleMenu models.RoleMenu
	var roleMenus []models.RoleMenu
	o := orm.NewOrm()
	// 获取 QuerySeter 对象，roleMenu 为表名
	qs := o.QueryTable(roleMenu.GetTableName())
	num, err := qs.Filter("RoleId", roleId).All(&roleMenus)
	if err == nil && num > 0 {
		for _, v := range roleMenus {
			data = append(data, v.AdminMenuId)
		}
	}
	return data
}
